// 页面进行渲染
// 定义一个函数
// 发送请求获取数据
// token 都是携带请求头中

// =====添加弹窗=====
const myModal = new bootstrap.Modal(document.querySelector('#modal'))

//  点击添加 弹窗
document.querySelector('#openModal').addEventListener('click', async function () {
    //    修改标题
    document.querySelector('.modal-title').innerHTML = '添加牛马学员'
    // 保存data-id=add
    document.querySelector('#submit').dataset.id = 'add'
    // 清空表单
    document.querySelector('#form').reset()
    // 重置省市区
    await Pprovince()
    await Ccity()
    await Aarea()

    myModal.show()
})
// 获取元素
const tbody = document.querySelector('tbody')
async function getStudents() {
    const res = await axios({
        url: "/students"
    })
    console.log(res.data);
    const { data } = res.data
    tbody.innerHTML = data.map((i) => {
        const { age, city, gender, id, province, name, group, hope_salary, salary, area
        } = i

        return `
                     <tr>
                      <td>${name}</td>
                      <td>${age}</td>
                      <td>${gender === 0 ? '男' : '女'}</td>
                      <td>第${group}组</td>
                      <td>${hope_salary}</td>
                      <td>${salary}</td>
                      <td>${province + city + area}</td>
                      <td>
                        <a href="javascript:;" class="text-success mr-3"><i data-id="${id
            }" class="bi bi-pen"></i></a>
                        <a  href="javascript:;" class="text-danger"><i data-id="${id
            }" class="bi bi-trash"></i></a>
                      </td>
                    </tr>
        `
    }).join('')
    // 设置学生有多少
    document.querySelector('.total').innerHTML = data.length
    console.log(data.length);
}
getStudents()

// ====删除====
tbody.addEventListener('click', async function (e) {
    // 判断是否点中这个类名
    let gmz
    // const myModal = new bootstrap.Modal(document.querySelector('#modal'))
    if (e.target.classList.contains('bi-trash')) {
        // 获取id
        const id = e.target.dataset.id
        gmz = await axios({
            url: `/students/${id}`,
            method: 'delete',
        })
        alert('删掉了')
        getStudents()

        // 判断是删除还是编辑
    } else if (e.target.classList.contains('bi-pen')) {
        // 弹出模态框
        myModal.show()
        // 把文字修改
        document.querySelector('.modal-title').innerText = '修改牛马'
        // 获取待编辑的id
        const id = e.target.dataset.id
        // 发送请求
        gmz = await axios({
            url: `/students/${id}`,

        })
        const { data } = gmz.data
        // 遍历对象
        for (const key in data) {
            const formEle = document.querySelector(`[name=${key}]`)

            if (formEle && key !== 'gender') {
                formEle.value = data[key]
            }
        }
        await Ccity()
        await Aarea()
        document.querySelector(`[name=gender][value='${data.gender}']`).checked = true

        if (document.querySelector('.modal-title').innerText == '修改牛马') {
            document.querySelector('#submit').onclick = async () => {
                const data = serialize(form, { hash: true, empty: true })
                console.log(111, data);
                for (const key in data) {
                    if (!isNaN(+data[key])) {
                        data[key] = +data[key]

                    } else {
                        data[key] = data[key]
                    }
                }
                console.log("www", data);

                gmz = await axios({
                    url: `/students/${id}`,
                    method: 'put',
                    data
                })
                myModal.hide()
                getStudents()
            }

        }
    }
})




// 添加======================
const form = document.querySelector('#form')
const btn = document.querySelector('#submit')
// 这里用onclick是为了给修改覆盖添加的点击事件 不让他们冲突
btn.onclick = async function (e) {
    // 阻止默认行为
    e.preventDefault()
    // 获取form表单的所有数据   前提的要引入form-serialize.js 库
    const data = serialize(form, { hash: true, empty: true })
    console.log('666', data);
    // 使用forin遍历对象
    for (const key in data) {
        if (!isNaN(+data[key])) {
            data[key] = +data[key]

        } else {
            data[key] = data[key]
        }
    }
    // 发送请求
    const res = await axios({
        url: '/students',
        method: 'post',
        data
    })
    console.log(res);
    alert('共鸣将傻逼')
    myModal.hide()
    getStudents()
}



// 获取省数据=============================================
async function Pprovince(province = '') {
    const res = await axios({
        url: '/api/province',
    })
    const { data } = res.data
    document.querySelector('[name=province]').innerHTML = data.map((i) => {
        return `<option value="${i}">${i}</option>`
    }).join('')
    if (province !== '') document.querySelector('[name=province]').value = province;
}
// Pprovince()

// 获取市
async function Ccity(city = '') {
    const pname = document.querySelector('[name=province]').value
    const res = await axios({
        url: '/api/city',
        params: {
            pname
        }
    })
    const { data } = res.data
    // 遍历data 市的数据
    document.querySelector('[name=city]').innerHTML = data.map((i) => {
        return `<option value="${i}">${i}</option>`
    }).join('')
    if (city !== '') document.querySelector('[name=province]').value = city;
}

// 获取区
async function Aarea(area = '') {
    // 获取省的值
    const pname = document.querySelector('[name=province]').value
    // 获取市的值
    const cname = document.querySelector('[name=city]').value
    // console.log('ppp', pname);
    const res = await axios({
        url: '/api/area',
        params: {
            pname,
            cname
        }
    })
    const { data } = res.data
    document.querySelector('[name=area]').innerHTML = data.map((i) => {
        return `<option value="${i}">${i}</option>`
    }).join('')
    if (area !== '') document.querySelector('[name=area]').value = area;
}
async function Sselect() {
    await Pprovince()
    await Ccity()
    await Aarea()
}
// 调用渲染省市区
Sselect()
// 省市区联动  绑定 change事件
document.querySelector('[name=province]').addEventListener('change', async function () {
    await Ccity()
    await Aarea()
})
// 市区联动  绑定 change事件
document.querySelector('[name=city]').addEventListener('change', async function () {
    await Aarea()
})



